package com.example.service;

import com.example.dto.LoginResult;
import com.example.mapper.TempUserMapper;
import com.example.mapper.UserMapper;
import com.example.pojo.TempUser;
import com.example.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private TempUserMapper tempUserMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private JavaMailSender mailSender;


    @Override
    public LoginResult loginCheck(String username, String password) {
        User user = userMapper.findByUsername(username);
        if (user == null) {
            return new LoginResult(0, "用户不存在", null);
        }
        if (!user.getPassword().equals(password)) {
            return new LoginResult(1, "密码错误", null);
        }
        return new LoginResult(2, "登录成功", user);
    }

    @Override
    public User findByUsername(String username) {
        return userMapper.findByUsername(username);
    }

    @Override
    public User findByEmail(String email) {
        return userMapper.findByEmail(email);
    }


    //验证邮箱账号 生成验证码
    @Override
    public String sendEmailCode(String email) {
        User user = userMapper.findByEmail(email);
        if (user == null) {
            return "NOT_FOUND";
        }

        String code = String.format("%06d", new Random().nextInt(999999));

        //保存验证码到Redis5分钟
        stringRedisTemplate.opsForValue().set("email:code:" + email, code, 5, TimeUnit.MINUTES);

        //异步操作 发送邮件
        sendMailAsync(email, code);

        return "OK";


    }

    @Async
    public void sendMailAsync(String toEmail, String code) {
        try {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setSubject("【图书管理系统】您的验证码");
            message.setText("验证码为：" + code + "，有效期5分钟，请及时输入。");
            message.setTo(toEmail);
            message.setFrom("3151470932@qq.com");
            mailSender.send(message);
        } catch (Exception e) {
            // 异常处理：记录日志或重试机制
            System.err.println("邮件发送失败：" + e.getMessage());
        }
    }

    // 专门负责发验证码，不做多余判断
    @Override
    public void sendCode(String email) {
        String code = String.format("%06d", new Random().nextInt(999999));
        ;
        stringRedisTemplate.opsForValue().set("email:code:" + email, code, 5, TimeUnit.MINUTES);
        sendMailAsync(email, code);
    }


    @Override
    // 验证验证码
    public boolean verifyEmailCode(String email, String code) {
        String cachedCode = stringRedisTemplate.opsForValue().get("email:code:" + email);
        return code != null && code.equals(cachedCode);
    }

    @Override
    public int saveUserTemp(TempUser user) {
        return tempUserMapper.insertTempUser(user);
    }


    //查找数据库是否存在Username
    @Override
    public boolean isUsernameExist(String username) {
        return userMapper.existsByUsername(username);
    }

    //保存用户信息
    public int saveUser(String username) {
        TempUser user = tempUserMapper.findUsername(username);
        System.out.println(user);
        User user1 = new User();
        user1.setUsername(user.getUsername());
        user1.setPassword(user.getPassword());
        user1.setEmail(user.getEmail());
        System.out.println(user1);
        return userMapper.insertUser(user1);
    }

    //删除临时用户
    public void deleteUserTemp(String username) {
        tempUserMapper.deleteTempUser(username);
    }
}

